<template>
	<div class="content">
		<div class="pageSearchView">
			<el-form :inline="true" :model="searchParam" class="demo-form-inline">
				<!-- <el-form-item label="领用人">
					<el-select v-model="searchParam.receiveUser" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="(item, index) in supplierList" :key="item.id" :value="item.id"
							:label="item.name">
						</el-option>
					</el-select>
				</el-form-item> -->
				<el-form-item label="领用仓库名称">
					<el-select v-model="searchParam.storageId" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in storageList" :key="item.id" :label="item.storageName"
							:value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
					<el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">
					<div>列表信息</div>
				</div>
				<div class="pageTableButView">
						<el-button @click="doOutIn()" :icon="Files">领用</el-button>
					<el-button  type="primary" @click="handleAdd" :icon="Plus">新建</el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table :data="paginatedData" height="calc(100vh - 320px)" row-key="id" :stripe="false"
				header-cell-class-name="witheTableHeader" @expand-change="handleExpandChange">
				<el-table-column type="expand">
					<template #default="scope">
						<!--            子级列表-->
						<div m="4">
							<el-table ref="tableCil" :stripe="false" border size="small" :data="scope.row.children"
                            style="width: 95%;margin-left: 20px" header-cell-class-name="blueTableHeader"
							@selection-change="(e)=>{handleSelectionChange(e,scope.row)}">
                            <el-table-column type="selection" width="60" align="center" :selectable="selectable" ></el-table-column>
                            <el-table-column type="index" width="80" label="" align="center" />
								<el-table-column label="物料名称" prop="materialName" min-width="150" align="center"
									show-overflow-tooltip />
								<el-table-column type label="数量" prop="count" min-width="150" align="center"
									show-overflow-tooltip />
									<el-table-column type label="状态" prop="type"
								:formatter="formatType"
								min-width="150" align="center"
                                show-overflow-tooltip />
							</el-table>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="序号" align="center" width="100">
					<template #default="scope"> {{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
				</el-table-column>
				<el-table-column label="工厂/车间" prop="organizationName" min-width="150" show-overflow-tooltip
					align="center" />
				<el-table-column label="领用人" prop="receiveUser" min-width="150" show-overflow-tooltip align="center" />
				<el-table-column label="领用仓库名称" prop="storageName" min-width="150" show-overflow-tooltip align="center" />
				<el-table-column label="备注" prop="remark" min-width="100" show-overflow-tooltip align="center" />

				<el-table-column label="创建时间" prop="createTime" min-width="150" show-overflow-tooltip align="center" />
				<el-table-column label="" min-width="80" align="center">
					<template #default="scopes">
						<el-button type="text" size="small" :icon="Files
							" @click="doOutIn(scopes.row)">领用
						</el-button>
					</template>
				</el-table-column>

			</el-table>
			<div class="pagePagination">
				<el-pagination background layout="sizes, prev,pager, next,total" :total="pageTotal" :page-size="pageSize"
					:current-page="currentPage" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</div>
		<!-- 编辑/新建弹框 -->
		<el-dialog v-model="showCrud" :title="crudTitle + '领用 '" width="1000px">
			<el-form ref="formRef" :model="formData" label-width="100px" :rules="outInRules">
				<el-row :gutter="10">
					<el-col :span="6">
						<el-form-item label="工厂/车间" style="width: 250px" prop="organizationId">
							<el-tree-select v-model="formData.organizationId" :data="workRoomList" check-strictly
								:props="{ children: 'sonList', label: 'orgName', value: 'id' }" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="领用人" style="width: 250px" prop="receiveUser">
							
							<el-input v-model="formData.receiveUser" placeholder="请输入领用人" clearable
												style="width:300px "></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="入库仓库">
							<el-tree-select v-model="formData.targetWarehouseId" :data="wareList" check-strictly
															:render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" @change="wareChange" />
						</el-form-item>
					</el-col>

					<el-col :span="6">
						<el-form-item label="领用仓库名称" prop="storageId" label-width="140px" >
							<el-select v-model="formData.storageId" placeholder="请选择" clearable filterable
								style="width: 400px">
								<el-option v-for="item in storageList" :key="item.id" :label="item.storageName"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<el-col :span="18">
						<el-form-item label="备注">
							<el-input v-model="formData.remark" style="width: 700px" :rows="3" type="textarea"
								placeholder="请输入备注" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<div class="pageTableTitle">物料列表</div>
				</el-row>
				<el-row :gutter="10" style="padding: 10px">
					<el-table :data="formData.childrenList" style="width:100% " height="300px">
						<el-table-column label="序号" type="index" align="center" width="80" />
						<el-table-column prop="materialId" label="物料编码" align="center">
							<template #default="scope">
								<el-select v-model="scope.row.materialId" :disabled="popType == 1" placeholder=""
									clearable filterable>
									<el-option v-for="item in materiaList" :key="item.value" :label="item.label"
										:value="item.value" />
								</el-select>
							</template>
						</el-table-column>
						<el-table-column prop="count" label="数量" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.count" type="number" :disabled="popType == 1"
									placeholder=""></el-input>
							</template>
						</el-table-column>

						<el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
							<template #header>
								<el-button :icon="Plus" text @click="handleAddConfigLine">新建</el-button>
							</template>
							<template #default="scope">

								<el-button type="danger" text :icon="Delete" @click="handleConfigDelete(scope.$index)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave(formRef)">保存</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {
	Delete, Edit, Tickets, DocumentChecked
	, Search, Share, Upload, Refresh, Plus, DocumentCopy, Files
} from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';


const paginatedData = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const searchParam = ref({});
const handleSizeChange = (val) => {
	pageSize.value = val;
	getList();
};
const handleCurrentChange = (val) => {
	currentPage.value = val;
	getList();
};


const formData = ref({
	planNo: '',
	name: '',
	planBeginTime: null,
	planEndTime: null,
	actualBeginTime: null,
	actualEndTime: null,
	organizationId: '',
	status: '0',
	type: '0'
});

const crudTitle = computed(() => {
	if (popType.value === 1) {
		return '查看';
	} else {
		return isEdit.value ? '编辑' : '新建';
	}
});

// 重置搜索条件
const resetSearch = () => {
	searchParam.value = {};
	currentPage.value = 1;
	// currentPage.value = 1
	getList();
};
const wareChange = (e) => {
	
	axiosInstance.post('/api/basedataStorage/listByPojoPage', {
		warehouseId: e,
		current: 1,
		pageSize: 999999
	})
		.then((res) => {
			if (res.code !== 200) {
				ElMessage.warning(res.message);
				return false;
			}
			storageList.value = res.data.records;
		});
};
const formatType = (row, column, cellValue) => {
  const typeMap = {
	0: '新建',
	1: '入库',
    2: '出库',
    3: '完结'
  };
  return typeMap[cellValue] || '';
}

const storageList = ref([]);
const materiaList = ref([]);
const formRef = ref(null);
const outInRules = reactive<FormRules<formRef>>({
    organizationId: [
        { required: true, message: '请选择工厂/车间', trigger: 'blur' }
    ],
    receiveUser: [
        { required: true, message: '请选择领用人', trigger: 'blur' }
    ],
    storageId: [
        { required: true, message: '请选择出库仓库名称', trigger: 'blur' }
    ]
});
const handleAddConfigLine = () => {
	formData.value.childrenList.push({
		materialId: null,
		materialCount: null,
		batchNo: null
	});
};

const selectedRows = ref([]); // 存储选中的行
const handleSelectionChange = (e,row) => {
  const dataPage=paginatedData.value.map(item=>{
	if(item.id===row.id){
		return {...item,childCheck:e}
	}
	return item
  })
  paginatedData.value=dataPage
};
const doOutIn = () => {
    ElMessageBox.confirm(
        '是否出库？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
       .then(async () => {
          const  checkItem=[]
		  paginatedData.value.map(item=>{
			if(item.childCheck){
				const ids=item.childCheck.map(i=>{
					return {
						id:i.id,
						type:2,
						count:i.count,
					}
				}
					
				)
				checkItem.push(...ids)
			}
		  })
		  console.log(checkItem,'checkItem')
		  axiosInstance.post('/api/sparePartDetail/updateTypeBatch',checkItem)
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			getList();
		});
       
        });
};


const handleConfigDelete = (e) => {
	formData.value.childrenList.splice(e, 1);
};

const workRoomList = ref([]);//车间
const supplierList = ref([]);
const wareList = ref([]);
const getOption = () => {

	axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
		if (res.code !== 200) {
			ElMessage.error(res.message);
			return false;
		}
		wareList.value = res.data;
	});
	// 领用人
	axiosInstance.post(`/api/basedataSupplier/getPage`, {
		current: 1,
		pageSize: 20
	}).then(res => {
		if (res.code == 200) {
			supplierList.value = res.data.records;
		}
	});

	axiosInstance.post('/api/basedataOrganization/getAll', {})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			workRoomList.value = res.data;
		});

	axiosInstance
		.post('/api/basedataMaterial/getAll', {}).then(res => {
			if (res.code == 200) {
				const list = res.data;
				const loop = [];
				for (const item of list) {
					loop.push(
						{
							value: item.id,
							label: item.materialName
						}
					);
				}
				materiaList.value = loop;
			}
		});

};


const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框


// 新建记录
const handleAdd = () => {
	if (formRef.value) {
		formRef.value.resetFields();
	}
	popType.value = 0;
	isEdit.value = false;
	formData.value = {
		childrenList: [{
			materialId: null,
			materialCount: null,
			batchNo: null
		}]
	};
	showCrud.value = true;
};


const popType = ref(0);//0 编辑 1 只读



// 保存记录
const handleSave = async (formEl: FormInstance | undefined) => {
	await formEl.validate((valid, fields) => {
		if (valid) {
			const param = {
				...formData.value,
				status: 2,
				
			};
			axiosInstance.post('/api/sparePart/save', param)
				.then((res) => {
					if (res.code !== 200) {
						ElMessage.error(res.message);
						return false;
					}
					showCrud.value = false;
					getList();
				});
		}
	});
};


const handleExpandChange = (row: any, expandedRows: any[]) => {
	if (expandedRows.includes(row)) {
		rowChildren(row);
	} else {
		// getList();
	}
};

const rowChildren = (row: any) => {
	axiosInstance.post('/api/sparePartDetail/getAll', { sparePartId: row.id }).then(res => {
		if (res.code !== 200) {
			ElMessage.warning(res.message);
			return false;
		}
		const listGroup = paginatedData.value.map((item) => {
			if (item.id === row.id) {
				return { ...item, children: res.data };
			}
			return item;
		});
		paginatedData.value = listGroup;
	});

};

const pageTotal = ref(0);

// 获取列表
const getList = async () => {
	paginatedData.value = [];
	axiosInstance.post('/api/sparePart/getPage', {
		...searchParam.value,
		current: currentPage.value,
		pageSize: pageSize.value,
		status: 2,

	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			paginatedData.value = res.data.records.map((item) => ({
				...item,
				children: [],
				layer: 1,
				_loading: false
			}));
			pageTotal.value = res.data.total;
		});
};

onMounted(() => {
	getList();
	getOption();
});
</script>
<style scoped lang="scss"></style>
